Deadlocks are a terminal locking issue that involves
two transactions. When the deadlock occurs one of the transactions is
killed and rolled back. A deadlock occurs when you have multiple
threads running against the same object at the same time, but the
transactions lock the same resources and then try to access the
resources locked by the other transaction. This can be shown most
easily with a diagram like the one in Figure 1.
As you can see in the figure, Transaction 1 begins and makes an update.
Transaction 2 begins at the same time, and attempts to make an update
but is blocked because of locks that Transaction 1 took on the table.
Transaction 1 then attempts to make another update to the table, but is
blocked because Transaction 2 now has a lock on the table. A deadlock
now has occurred because there is no way for either transaction to ever
complete no matter how long they wait. When the deadlock occurs one of
the transactions is killed and the second is allowed to complete. The
transaction that has been killed will be rolled back and the session
disconnected. An error is also logged to SQL Server ERRORLOG when a
deadlock occurs.
If
your application is suffering from deadlocks you have a few options to
resolve the issue. You can start by reducing the length of time for
which your transactions are held. As the transactions complete more
quickly your deadlocks should be reduced as the length of time that the
locks are held for is reduced. Another option is to combine your
commands into a single command as this will stop Transaction 1 from
needing to wait for Transaction 2 to complete.
A
system that has lots of deadlocks can be very difficult to handle,
especially if your transactions are already short. If your system load
is high enough and your transactions are already as short as they can
be, you may not be able to do anything.
At
one finance company that I worked for our OLTP load origination system
was having a large number of deadlocks on a daily basis. We reviewed
our system, and found that our transactions were as short as they could
be. Because of the extremely high load on our system it turned out that
a hardware upgrade was the only way to get the system to process the
transactions any faster.
|
If
you are getting a lot of deadlocks are you are not sure which
statements are causing the deadlocks you can enable trace flags 1204
and 1222. These trace flags will output information about the deadlock
to the ERRORLOG file, which will enable you to find the statements that
are causing the deadlocks as well as which statement is being killed.